/* 
 * File:   newmain.c
 * Author: Andras Veres
 *
 * Wactchdog code written for PIC12F683
 * If there is no level change on port5 within 1 second, port4 goes down
 * There is a weak pull-up on the input port
 *
 * Created on 2013. augusztus 10., 9:50
 */

#include <stdio.h>
#include <stdlib.h>

#include <xc.h>

// CONFIG
#pragma config FOSC = INTOSCIO  // Oscillator Selection bits (INTOSCIO oscillator: I/O function on RA4/OSC2/CLKOUT pin, I/O function on RA5/OSC1/CLKIN)
#pragma config WDTE = OFF       // Watchdog Timer Enable bit (WDT disabled)
#pragma config PWRTE = OFF      // Power-up Timer Enable bit (PWRT disabled)
#pragma config MCLRE = ON       // MCLR Pin Function Select bit (MCLR pin function is MCLR)
#pragma config CP = OFF         // Code Protection bit (Program memory code protection is disabled)
#pragma config CPD = OFF        // Data Code Protection bit (Data memory code protection is disabled)
#pragma config BOREN = OFF      // Brown Out Detect (BOR disabled)
#pragma config IESO = ON        // Internal External Switchover bit (Internal External Switchover mode is enabled)
#pragma config FCMEN = ON       // Fail-Safe Clock Monitor Enabled bit (Fail-Safe Clock Monitor is enabled)

#define _XTAL_FREQ 4000000
#define IN  GPIObits.GP5
#define OUT GPIObits.GP4

/*
 * 
 */
int main(int argc, char** argv) {


    GPIO = 0;           // init GPIO
    CMCON0 = 0x07;      // Switch off comaparator on outputs
    ANSEL = 0;          // Set all analog pins to digital (not use as AD inputs)
    TRISIO = 0b00100000;         // Set all IO ports as output except port5

    OPTION_REGbits.nGPPU = 0; // GPIO pull-ups are individually set by
    WPUbits.WPU5 = 1;         // pul-up enabled on port 5

    char last = IN;
    int wait = 0;

    while(1) {

       __delay_ms(1);

       if(IN == last) {
          if(wait>0) wait--;
       } else wait = 1000;

       if(wait==0) OUT = 0;
       else OUT = 1;

       last = IN;
    }

    return (EXIT_SUCCESS);
}

